package BNS.wheat;

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import BNS.graphs.*;

/** Used by WheatMktPersona to display buying and selling prices in a local market */
public class MarketPanel extends JPanel {
	
	public static final Color 
		money=  new Color(50,250,50),
		wheat=  new Color(230,200,0);
	
	// The following line stops a compiler warning:
	private static final long serialVersionUID = 0L;
	
	protected Image offscreen;
    protected Dimension window, offscreensize;
    protected Graphics offgraphics;
//	protected FontMetrics fontmetrics;
//	protected int halfChar;
	
	protected Graph graph;
	protected Market market;
	private PricesChart supplierPrices, suppliedPrices;
	private NodeState[] nodeStates;
	
	/** Shows a PricesChart for both suppliers and consumers
		@param gr the Graphlet that describes this player's neighbourhood 
		@param mkt the Market that describes prices in this neighbourhood 
		*/
	public MarketPanel(Graph gr, Market mkt) { //, TradePanel tp?
		market= mkt;
		graph= gr;
		// much initialization work is done in ready() when window gets resized
		}
	
	public void rebuild(NodeState[] ns) { 
		nodeStates= ns; 
//		market.rebuild(ns);		// done in MarketGamePersona
		repaint(); 
		}
	
	/** If the window has been resized, then offgraphics is re-initialized.
		Clears offgraphics by painting it with background color.
		TODO: make this private */
	public void ready(Graphics g) {
		window= getSize();
		//System.err.println("gPanel paint "+ window +" graph="+ graph);
		if ((offscreen==null) || (window.width != offscreensize.width) 
			|| (window.height != offscreensize.height)) {
			offscreen= createImage(window.width, window.height);
			offscreensize= window;
			offgraphics= offscreen.getGraphics();
			offgraphics.setFont(getFont());
//			fontmetrics= offgraphics.getFontMetrics();
//			halfChar= fontmetrics.getAscent()/2;
			
			int vbreak= (int)(window.height-20);
			supplierPrices= new PricesChart(10,10,window.width-20,vbreak-10,true,graph);
			}
		offgraphics.setColor(getBackground());
		offgraphics.fillRect(0,0,window.width, window.height);
		}
	
	/** Paint the entire MarketPanel using local variables.
		Called by the windowing system whenever it thinks this panel needs to be redrawn. */
	public synchronized void paint(Graphics g) {
		ready(g);
		if (nodeStates==null) {
			g.setColor(getBackground());
			g.fillRect(0,0, window.width, window.height);
			g.setColor(Color.black);
			//System.err.println("GraphPanel paint: "+ waitMessage);
			g.drawString("setting up MarketPanel", 20,50);
			return;
			}
		supplierPrices.paint(offgraphics,nodeStates);
		g.drawImage(offscreen, 0,0, null);
		}
	}
